package com.xique.blelock.view.AcountManager;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.Utils.ACache;
import com.xique.blelock.Utils.MyActivityManager;
import com.xique.blelock.Utils.SettingManager;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.UserInfo;
import com.xique.blelock.view.BaseActivity;
import com.xique.blelock.R;

import org.json.JSONException;
import org.json.JSONObject;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

public class Myself_Activity extends BaseActivity implements View.OnClickListener {
    private AlertDialog dialog3;
    private LinearLayout Mpasswordset,Mhelpcenter, Mideafankun;
    private ImageView Back;
    private TextView username;
    private Button Mout;
    private String TAG = "Myself_Activity";
    private String uidflag = "1";
    private String tokenflag1 = "1";

    @BindView(R.id.edituser)
    TextView edituser;

    private static final int MODIFYUSER = 10001;

    //设置密码
    private static final int SETTINGPWD = 10002;

    @BindView(R.id.headbtn)
    ImageView headview;

    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.pwdsetting)
    TextView pwdsetting;


    // 获取用户新
    private UserInfo userInfo;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myselfcent_activity);//个人中心
        ButterKnife.bind(this);
        initview();
    }

    private void initview() {
//        Msex = findViewById(R.id.gender);

        Back = findViewById(R.id.BACKER);
        Mpasswordset   = findViewById(R.id.PASSWORDSET);
        Mhelpcenter = findViewById(R.id.helpcent);
        Mideafankun = findViewById(R.id.yijianfankun);
        Mout = findViewById(R.id.outzahnghao);

        Back.setOnClickListener(this);
        Mhelpcenter.setOnClickListener(this);
        Mpasswordset.setOnClickListener(this);
        Mideafankun.setOnClickListener(this);
        Mout.setOnClickListener(this);

        title.setText("个人中心");

        showUserInfo();

    }

    @OnClick({R.id.edituser, R.id.headbtn})
    public void edituserinfo(){
        Intent serverIntent = new Intent(this, Ediot_Activity.class); // 跳编辑界面
        startActivityForResult(serverIntent, MODIFYUSER);

    }

    //关于我们
    @OnClick(R.id.aboutus)
    public void jumpAboutUs(){
        //aboutus
        Intent intent = new Intent(this, AboutUsActivity.class);
        startActivity(intent);

    }

    @OnClick(R.id.BACKER)
    public void BackLastPage(){
        finish();
    }


    private void showUserInfo(){
        userInfo = (UserInfo) ACache.get(this).getAsObject(Stringkey.USERInfo);


        if(userInfo == null){
            showToast(this, "还没有设置用户信息");
            return;
        }
        if(!TextUtils.isEmpty(userInfo.getNickname()))
        {
            edituser.setText(userInfo.getNickname());
        }


        if(userInfo.getIssetPwd() == 0){
            pwdsetting.setText("设置密码");
        }else{
            pwdsetting.setText("修改密码");
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == MODIFYUSER){
            userInfo = (UserInfo) ACache.get(this).getAsObject(Stringkey.USERInfo);
            showUserInfo();
        }else if(requestCode == SETTINGPWD && (resultCode== RESULT_OK)){
            userInfo = (UserInfo) ACache.get(this).getAsObject(Stringkey.USERInfo);
            if(userInfo.getIssetPwd() == 0){
                pwdsetting.setText("设置密码");
            }else{
                pwdsetting.setText("修改密码");
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == Back) {//返回
            finish();
        }else if (v == Mpasswordset) {//密码设置
            Intent serverIntent = new Intent(this, Passset_Activity.class); // 跳转密码设置
            startActivityForResult(serverIntent,SETTINGPWD);
        }else if (v == Mhelpcenter) {//帮助中心
            Intent serverIntent = new Intent(this, Helpcent_Activity.class); // 跳帮助中心
            startActivity(serverIntent);
        }else if (v == Mideafankun) {//意见反馈
            Intent serverIntent = new Intent(this, Idea_activity.class); // 跳转意见反馈
            startActivity(serverIntent);
        } else if (v == Mout) {

            quitTipDialog();
        }
    }

    private void quitTipDialog() {

        new MaterialDialog.Builder(this)
                .title("提示")// 标题
                .titleColor(getResources().getColor(R.color.tipstitle))
                .backgroundColor(getResources().getColor(R.color.white))
                .content("确定要退出")// 内容
                .contentColor(Color.BLACK)// 内容颜色
                .positiveText("确定")
                .positiveColorRes(R.color.cologbtnhou)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        outzhanghao();
                    }
                })
                .negativeText("取消")
                .negativeColorRes(R.color.cancle)
                .show();

    }

    /**
     * 退出账号
     */
    private void outzhanghao() {

            XqNetClient netClient =  new XqNetClient();
            JSONObject jsonobject = new JSONObject();
            try {
                jsonobject.put("token", userInfo.getToken());
                jsonobject.put("uid", userInfo.getUid());
                jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            netClient.sendAuthCode4(jsonobject.toString()).enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    System.out.println("-===获取的验证码是："+ response.body());
                    Log.e(TAG, "-===获取退出登录信息：" + response.body());
                    String code = "1";
                    try {
                        JSONObject jsonObject = new JSONObject(response.body());
                        code = jsonObject.getString("message");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (code.equals("成功")) {//如果成功就跳转到主界面
                        Toast.makeText(Myself_Activity.this,"退出登陆",Toast.LENGTH_SHORT).show();
                        ACache.get(Myself_Activity.this).clear();
                        SettingManager.getInstance(Myself_Activity.this).clean();
                        Intent serverIntent = new Intent(Myself_Activity.this, Login_Activity.class); // 跳转注册界面

                        startActivity(serverIntent);

                        MyActivityManager.finishAll();
                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    t.printStackTrace();
                }
            });

    }
    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "收到数据 uid"+uidflag+"收到数据token"+tokenflag1);
    }



    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
